package com.eco.mam.work.request;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.eco.mam.work.ConfigParameters;
import com.eco.mam.work.DataException;
import com.eco.mam.work.request.dto.WorkRequest;
import com.eco.mam.work.request.resource.WorkRequestConfig;
import com.eco.mam.work.request.transform.XMLTransformHelper;
import com.eco.mam.work.request.transform.XMLTransformer;

public class WorkRequestProcessor {
    static final Logger logger = Logger.getLogger(WorkRequestProcessor.class);
    public boolean process() {
        logger.info("Entering mehthod WorkRequestProcessor.process() ");
        /* loading the csv file as a stream by passing the csv file name */
        BufferedReader reader = null;
        StringWriter stringWriter = null;
        boolean success = true;
        try {
            String strFileName = WorkRequestConfig.getFileName(ConfigParameters.CSV_INPUT_FILE);
            File file = new File(strFileName);
            FileReader fileReader = new FileReader(file);
            reader = new BufferedReader(fileReader);
            if (logger.isDebugEnabled()) {
                logger.debug("buffer reader  :" + reader);
            }
            Map map = prepareValidandInvalidWorkRequests(reader);
            stringWriter = new XMLTransformer().transform((ArrayList<String[]>) map.get("strCsvTokensList"));
            WorkRequestUtils workRequestUtils = new WorkRequestUtils();
            workRequestUtils.writeToConsole(stringWriter);
            workRequestUtils.writeToFile(stringWriter);
            workRequestUtils.writeToFile(((StringBuffer)map.get("missingData")));
            workRequestUtils.writeToFile((((ArrayList<String>)map.get("invalidWorkRequests"))));
            
            
        } catch (DataException e) {
            success = false;
            if (logger.isDebugEnabled()) {
                logger.debug(e);
            }
        } catch (FileNotFoundException e) {
            success = false;
            if (logger.isDebugEnabled()) {
                logger.debug(e);
            }
        } catch (IOException e) {
            success = false;
            if (logger.isDebugEnabled()) {
                logger.debug(e);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    logger.debug(e);
                }
            }
        }
        return success;
    }

    /**
     * @param reader
     * @return
     * @throws IOException
     */
    private Map prepareValidandInvalidWorkRequests(BufferedReader reader)
            throws IOException {
        ArrayList<String> invalidWorkRequestsList = new ArrayList<String>();
        ArrayList<WorkRequest> validWorkRequestsList = new ArrayList<WorkRequest>();
        String strCsvHeader = reader.readLine();
        invalidWorkRequestsList.add(strCsvHeader);
        String strCsvHeaders[] = strCsvHeader.split(",");
        String strCsvValues = null;
        String strCsvTokens[] = null;
        ArrayList<String[]> strCsvTokensList = new ArrayList<String[]>();
        StringBuffer missingDataInforamtion=new StringBuffer();
        int lineNo=0;
        while ((strCsvValues = reader.readLine()) != null) {
            lineNo=++lineNo;
            strCsvTokens = strCsvValues.split(",");
            Map validationResult = new WorkRequestCsvDataValidator()
                    .validate(strCsvTokens,lineNo);
            Boolean validWorkRequest=(Boolean) validationResult.get("validate");
            if (validWorkRequest == false) {
                invalidWorkRequestsList.add(strCsvValues);
                missingDataInforamtion.append(validationResult.get("missingData")).append("\n");
           
            }
            if (validWorkRequest == true) {
                strCsvTokensList.add(strCsvTokens);
                WorkRequest workRequest = new WorkRequestProcessHelper()
                        .createWorkRequestObjectFromCsvStringTokens(strCsvTokens);
                validWorkRequestsList.add(workRequest);
            }
        }
        
        Map map = new HashMap();
        map.put("invalidWorkRequests", invalidWorkRequestsList);
        map.put("strCsvTokensList", strCsvTokensList);
        map.put("validWorkRequestsList", validWorkRequestsList);
        map.put("missingData", missingDataInforamtion);
        return map;
    }

}
